/**
 * Echarts 工具包
 * @author 木人心
 * @version 1.0.1
 */
import { ECharts } from 'echarts'
import lodash from '@utils/lodash'
import { LinearGradientObject } from 'echarts/types/dist/echarts'

/**
 * 获取纵向的渐变色
 * @param startColor : String 起始颜色
 * @param endColor : String? 结束颜色，为空时生成起始颜色的透明色
 * @param direction
 * @returns {}
 */
function getLinearGradient (startColor: string, endColor?: string, direction: 'horizontal' | 'vertical' = 'vertical'): LinearGradientObject {
  // 如果endColor不存在，则生成一个与startColor同色的透明色
  if (!endColor) {
    // 如果是HEX
    if (/^#[0-9A-Fa-f]{6}|[0-9A-Fa-f]{3}$/.test(startColor)) {
      // 如果是6位
      if (/^#[0-9A-Fa-f]{6}$/.test(startColor)) {
        endColor = startColor + '00'
      } else {
        endColor = startColor + '0'
      }
    } else if (/^rgba?\((.*)\)$/.test(startColor)) { // 如果是RGB或RGBA
      const valueArr = startColor.replace(/^rgba?\((.*)\)$/, '$1').split(',').map(item => {
        return Number(item)
      })
      valueArr[3] = 0
      endColor = `rgba(${valueArr.join(',')})`
    }
  }
  let _direction = { x: 0, y: 0, x2: 0, y2: 1 }
  if (direction === 'horizontal') {
    _direction = { x: 0, y: 0, x2: 1, y2: 0 }
  }
  return {
    type: 'linear',
    ..._direction,
    colorStops: [{
      offset: 0,
      color: startColor
    }, {
      offset: 1,
      color: endColor
    }],
    global: false
  }
}

// region TODO Resize 监听器
const resizePool = new Map<Element, ECharts>()
const resizeObserver = new ResizeObserver(lodash.debounce((entries) => {
  for (let i = 0, len = entries.length; i < len; i++) {
    resizePool.get(entries[i].target)?.resize()
  }
}, 50))
// endregion

export const EChartsUtil = {
  /**
   * 添加Resize监听器
   * @param chart
   */
  addResizeListener (chart: ECharts | ECharts[]) {
    if (Array.isArray(chart)) {
      for (let i = 0, len = chart.length; i < len; i++) {
        const item = chart[i]
        const dom = item.getDom()
        resizeObserver.observe(dom)
        resizePool.set(dom, item)
      }
    } else {
      const dom = chart.getDom()
      resizeObserver.observe(dom)
      resizePool.set(dom, chart)
    }
  },

  /**
   * 移除Resize监听器
   * @param chart
   */
  removeResizeListener (chart: ECharts | ECharts[]) {
    if (Array.isArray(chart)) {
      for (let i = 0, len = chart.length; i < len; i++) {
        const item = chart[i]
        const dom = item.getDom()
        resizeObserver.unobserve(dom)
        resizePool.delete(dom)
      }
    } else {
      const dom = chart.getDom()
      resizeObserver.unobserve(dom)
      resizePool.delete(dom)
    }
  },

  getLinearGradient
}
